package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;

import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.domin.ProductSku;
import com.spzx.product.vo.SkuLockVo;
import com.spzx.product.vo.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-05-09
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private RemoteCartService remoteCartService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private RemoteUserAddressService remoteUserAddressService;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Autowired
    private RemoteSkuStockService remoteSkuStockService;
    @Autowired
    private RabbitService rabbitService;
    @Override
    public TradeVo gettrade() {
        TradeVo tradeVo = new TradeVo();
        //获取购物车中的详细信息列表
        R<List<CartInfo>> r =
                remoteCartService.getcartcheckedlist(SecurityConstants.INNER);
        //验证远程调用是否成功
        if (R.FAIL==r.getCode()){
            throw new ServiceException("远程服务调用失败");
        }
        List<CartInfo> data = r.getData();
        if (ObjectUtils.isEmpty(data)){
            throw new ServiceException("没有要结算的商品");
        }
        //将购物车商品列表转为订单明细列表
        List<OrderItem> orderItems = data.stream()
                .map(cartInfo -> {
                    OrderItem orderItem = new OrderItem();
                    BeanUtils.copyProperties(cartInfo, orderItem);
                    return orderItem;
                }).collect(Collectors.toList());
        tradeVo.setOrderItemList(orderItems);
        //计算商品的全部金额
        BigDecimal allamount = new BigDecimal(0);
        for (OrderItem orderItem : orderItems) {
            allamount= allamount
                    .add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        tradeVo.setTotalAmount(allamount);

        //生成订单流水号,防止重复校验,存入redis有效期五分钟
        String tradeNo = this.generateTradeNo();
        tradeVo.setTradeNo(tradeNo);
        //将TradeVo返回
        return tradeVo;
    }

    @Override
    public String generateTradeNo() {
        //生成订单流水号
        String tradeKey = "user:tradeNo:" + SecurityContextHolder.getUserId();
        String TradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeKey,TradeNo,5, TimeUnit.MINUTES);
        return TradeNo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long submitOrder(OrderForm orderForm) {
        //校验流水号,防止订单重复和长时间停留
        String tradeKey = "user:tradeNo:" + SecurityContextHolder.getUserId();
        //通过lua脚本验证
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end\n";
        RedisScript<Boolean> booleanRedisScript = new DefaultRedisScript<>(script, Boolean.class);
        Boolean flag = (Boolean) redisTemplate
                .execute(booleanRedisScript, Arrays.asList(tradeKey), orderForm.getTradeNo());
        if (!flag){
            throw new RuntimeException("流水校验失败,重新提交");
        }
        //验证订单中的价格有无变化
        //根据订单列表中的skuid  远程调用商品微服务查取价格
        List<Long> list = orderForm.getOrderItemList().stream().map(OrderItem::getSkuId)
                .collect(Collectors.toList());
        R<List<SkuPriceVo>> r = remoteProductService
                .getskupricelist(list, SecurityConstants.INNER);
        if (r.getCode()==R.FAIL){
            throw new ServiceException("远程调用服务失败"+r.getMsg());
        }
        List<SkuPriceVo> data = r.getData();
        //校验价格是否被更改
        Map<Long, BigDecimal> bigDecimalMap = data.stream()
                .collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        String priceErrorMsg ="";
        for (OrderItem orderItem : orderForm.getOrderItemList()) {
            if (orderItem.getSkuPrice().compareTo(bigDecimalMap.get(orderItem.getSkuId()))!=0){
            //两者比较不等于0说明价格发生了改变
            priceErrorMsg += orderItem.getSkuName()+"\n";
            }
        }
        if (!ObjectUtils.isEmpty(priceErrorMsg)){
            //直接通过购物车提交的订单,则远程调用购物车服务更新商品价格
            if (!orderForm.getIsBuy()){
                remoteCartService.updateCartPrice(SecurityConstants.INNER);
            }
            //提示价格又变化,重新结算
            throw new ServiceException(priceErrorMsg+"以上商品价格有变动");
        }

        //如果价格没变保存订单信息,明细,日志
        OrderInfo orderInfo = this.saveOrder(orderForm);
        // 尝试检查锁定商品库存，远程调用商品服务库存锁定
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            BeanUtils.copyProperties(orderItem, skuLockVo);
            return skuLockVo;
        }).collect(Collectors.toList());
        R<String> r1 = remoteSkuStockService.checkAndLock(orderInfo.getOrderNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == r1.getCode()) {
            throw new ServiceException("库存锁定失败，原因：" + r1.getMsg());
        }
        String stockErrorMsg = r1.getData();
        if (StringUtils.isNotBlank(stockErrorMsg)) {
            throw new ServiceException(stockErrorMsg);
        }

        //保存订单成功后， 如果是通过购物车车途径提交订单，清理用户购物车
        if (!orderForm.getIsBuy()) {
            remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);
        }
        //响应订单ID，对接支付页
        return orderInfo.getId();

    }

    @Override
    public OrderInfo saveOrder(OrderForm orderForm) {
        //保存订单信息
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        //1.1用户信息
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        //1.2生成订单编号,格式:日期加全局唯一id(雪花算法)
        String orderNo = DateUtils.dateTime() + IdWorker.getIdStr();
        orderInfo.setOrderNo(orderNo);
        //1.3遍历明细计算订单的总金额
        /*BigDecimal totalAmount = orderForm.getOrderItemList().stream()
                .map(OrderItem::getSkuPrice)
                //从0开始累加结合中每个元素值
                .reduce(BigDecimal.ZERO, BigDecimal::add);*/
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderForm.getOrderItemList()) {
            totalAmount=totalAmount
                    .add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        //1.4订单状态设为待付款
        orderInfo.setOrderStatus(0);
        orderInfo.setCreateBy(userName);
        orderInfo.setRemark(orderForm.getRemark());
        //1.5封装收件人信息,远程调用用户服务拿到
        R<UserAddress> r = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER);
        if (r.getCode()==R.FAIL){
            throw new ServiceException("远程调用用户服务失败,原因:"+r.getMsg());
        }
        UserAddress userAddress = r.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getAddress());
        save(orderInfo);
        Long orderInfoId = orderInfo.getId();
        //2保存订单明细信息
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (!ObjectUtils.isEmpty(orderItemList)){
            for (OrderItem orderItem : orderItemList) {
                orderItem.setOrderId(orderInfoId);
                orderItem.setCreateBy(userName);
                orderItemMapper.insert(orderItem);
            }
        }
        //3保存订单操作日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfoId);
        orderLog.setOperateUser(userId.toString());
        orderLog.setProcessStatus(0);
        orderLog.setNote(orderForm.getRemark());
        orderLog.setCreateBy(userName);
        orderLog.setCreateTime(new Date());
        orderLogMapper.insert(orderLog);
        return orderInfo;
    }

    @Override
    public TradeVo buy(Long skuId) {
        //1.创建订单确认VO对象
        TradeVo tradeVo = new TradeVo();
        //2.封装订单明细
        //2.1 远程调用"商品服务"查询商品信息
        R<ProductSku> r = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == r.getCode()) {
            throw new ServiceException("远程调用商品服务失败，原因：" + r.getMsg());
        }
        ProductSku productSku = r.getData();
        //2.2 封装订单明细列表
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        List<OrderItem> orderItemList = Arrays.asList(orderItem);
        tradeVo.setOrderItemList(orderItemList);
        //3.封装订单总金额
        tradeVo.setTotalAmount(orderItem.getSkuPrice());
        //4.生成流水号
        String tradeNo = this.generateTradeNo();
        tradeVo.setTradeNo(tradeNo);
        //5.设置立即购买为：true
        tradeVo.setIsBuy(true);
        return tradeVo;
    }

    @Override
    public List<OrderInfo> userOrderInfoList(Long userId, String orderStatus) {
        //1.查询订单列表
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getUserId,SecurityContextHolder.getUserId())
                .eq(!ObjectUtils.isEmpty(orderStatus),OrderInfo::getOrderStatus,orderStatus)
                .orderByDesc(OrderInfo::getCreateTime);
        List<OrderInfo> orderInfoList = list(orderInfoLambdaQueryWrapper);
        //2.查询订单明细列表,将订单明细列表封装到订单信息中
        if (!ObjectUtils.isEmpty(orderInfoList)){
            List<Long> list = orderInfoList.stream().map(OrderInfo::getUserId).collect(Collectors.toList());
            LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper = new LambdaQueryWrapper<>();
              orderItemLambdaQueryWrapper.in(OrderItem::getOrderId, list);
            List<OrderItem> orderItems = orderItemMapper.selectList(orderItemLambdaQueryWrapper);
            //把查出来的明细封装到订单中,按照订单id进行分组分装,然后在装进orderinfo对象中
            Map<Long, List<OrderItem>> collect = orderItems.stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderId));
            for (OrderInfo orderInfo : orderInfoList) {
                orderInfo.setOrderItemList(collect.get(orderInfo.getId()));
            }
        }
        return orderInfoList;
    }

    @Override
    //取消订单
    public void cancelOrder(Long orderId) {
        //1.根据订单ID查询订单信息
        OrderInfo orderInfo = getById(orderId);
        //2.判断订单状态 如果是未支付才可以取消
        if (orderInfo != null && orderInfo.getOrderStatus() == 0) {
            orderInfo.setOrderStatus(-1);
            updateById(orderInfo);
            //3. 基于RabbitMQ解除锁定库存,生产者发送订单的编号
            rabbitService.sendMessage(
                    MqConst.EXCHANGE_PRODUCT,
                    MqConst.ROUTING_UNLOCK,
                    orderInfo.getOrderNo()
            );
        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        //1.查询订单信息
        OrderInfo orderInfo = this.getOne(
                new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
        );
        //2.查询订单明细列表
        if (orderInfo != null) {
            LambdaQueryWrapper<OrderItem> orderItemLambdaQueryWrapper
                    = new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId());
            List<OrderItem> orderItemList = orderItemMapper.selectList(orderItemLambdaQueryWrapper);
            orderInfo.setOrderItemList(orderItemList);
        }
        return orderInfo;
    }

    @Override
    public void paymentSuccess(String orderNo) {
        OrderInfo orderInfo = this.getByOrderNo(orderNo);
        if (orderInfo.getOrderStatus().intValue()==0) {
            orderInfo.setOrderStatus(1);
            this.updateById(orderInfo);
        }
    }


}
